package com.da.javatest.leetCode;

/**
 * @author chenlida
 * @date 2018/12/8 11:54
 * @description
 */
public class AddTwoNumber {
    private ListNode result;
    private boolean flag = false;

    public static void main(String[] args) {
        AddTwoNumber number = new AddTwoNumber();
        ListNode l1 = new ListNode(1);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        ListNode listNode = number.addTwoNumbers(l1, l2);
        System.out.println(listNode.val);
        System.out.println(listNode.next.val);
        System.out.println(listNode.next.next.val);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int r = l1.val + l2.val;
        if (flag) {
            flag = false;
            r += 1;
        }
        if (result == null) {
            if (r > 9) {
                flag = true;
                result = new ListNode(r % 10);
            } else {
                result = new ListNode(r);
            }
        } else {
            if (r > 9) {
                flag = true;
                getNullNode(result).next = new ListNode(r % 10);
            } else {
                getNullNode(result).next = new ListNode(r);
            }
        }
        if (l1.next != null && l2.next != null) {
            return addTwoNumbers(l1.next, l2.next);
        } else if (l1.next != null) {
            return addTwoNumbers(l1.next, new ListNode(0));
        } else if (l2.next != null) {
            return addTwoNumbers(new ListNode(0), l2.next);
        }
        if (flag) {
            getNullNode(result).next = new ListNode(1);
        }

        return result;
    }

    private ListNode getNullNode(ListNode r) {
        if (r.next != null) {
            return getNullNode(r.next);
        }
        return r;
    }

}

